package com.epoint.mobileoa.ui.main;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.ConfigKey;
import com.epoint.mobileoa.bizlogic.FrameMethod;
import com.epoint.mobileoa.bizlogic.PersonalMainView;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.bizlogic.icon.IconInfo;
import com.epoint.mobileoa.db.DBHelp;
import com.epoint.mobileoa.http.HttpHelp;
import com.epoint.mobileoa.personalized.epointcompany.ui.kaoqing.KaoQingDetailView;
import com.epoint.mobileoa.service.MainService;
import com.epoint.mobileoa.tools.AlertHelp;
import com.epoint.mobileoa.tools.Arithmetic;
import com.epoint.mobileoa.tools.EpointDialog;
import com.epoint.mobileoa.tools.LogHelp;
import com.epoint.mobileoa.tools.PropertiesHelp;
import com.epoint.mobileoa.tools.StringHelp;
import com.epoint.mobileoa.tools.ToastHelp;
import com.epoint.mobileoa.tools.dialog.SuperDialog;
import com.epoint.mobileoa.ui.ds.DSView;
import com.epoint.mobileoa.ui.login.LoginView;
import com.epoint.mobileoa.ui.mail.MailMain;
import com.epoint.mobileoa.ui.update.UpdateView;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Handler;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * @author liyc
 * @time 2012-1-9 下午6:23:46
 * @annotation 主界面
 */
public class MainView extends SuperView {
	private GridView gv;
	private ListView lv;
	private TextView title_tv_realname;
	private boolean isUpdateName;
	public static Thread updateNameThread;//更新标题栏姓名线程
	private TextView title_prjname;
	private PersonalMainView pmv;
	private ImageView ivMailTip;

	private Map<String,IconInfo> listtemp = new HashMap<String, IconInfo>();

	private List<IconInfo> list;



	@Override
	public void initControls(){
		try{
			ivMailTip = (ImageView) findViewById(R.id.ivMailTip);
			title_prjname = (TextView) findViewById(R.id.title_prjname);
			title_prjname.setText(getString(R.string.prjname)+"V"+getString(R.string.version));
			String pmvname = PropertiesHelp.getProperty(this, "PersonalMainView");
			Class<?> clazz =Class.forName(pmvname);
			Constructor<?> constructor = clazz.getConstructor(SuperView.class);
			pmv = (PersonalMainView) constructor.newInstance(this);

			MainService.isrefreshloginstatusflag = true;
			//		topmenu.setVisibility(View.GONE);
			top_left_bt.setVisibility(View.GONE);
			gv = (GridView) findViewById(R.id.ecm_gv);
			gv.setOnItemClickListener(this);
			gv.setOnItemLongClickListener(this);

			title_tv_realname = (TextView) findViewById(R.id.title_tv_realname);
			//欢迎
			showWelcome(this);
			//是否开通提示
			Tip(this);
			//检测更新
			ShowUpdate(this);
			lv = (ListView) findViewById(R.id.lvIcon);
			lv.setOnItemClickListener(this);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public static String[] titles;
	public static int[] defaultPosition;

	public void setIcon(){

		defaultPosition = pmv.getPositions();

		list = new ArrayList<IconInfo>();

		int[] imgs = pmv.getImgs();

		com.epoint.mobileoa.bizlogic.icon.IconInfo.OnClickListener[] iconOnclicks
		= pmv.getOnClickListener();

		titles = pmv.getTitles();

		Class[] intentViews = pmv.getIntentViews();

		String positionstr = DBHelp.getConfigValue(this, ConfigKey.mainviewPositionStr);

		int[] positions = null;
		if(!positionstr.equals("")){
			String[] positionstrs = positionstr.split(";");
			if(positionstrs.length!=titles.length){
				positions = pmv.getPositions();
			}
			else{
				positions = new int[positionstrs.length];
				for(int i=0;i<titles.length;i++){
					positions[i] = Integer.parseInt(positionstrs[i]);
				}
			}
		}
		else{
			positions = pmv.getPositions();
		}

		int[] show = getShow();

		for(int i=0;i<positions.length;i++){
			IconInfo ii = new IconInfo(imgs[i], titles[i], positions[i],intentViews[i],show[i]);
			ii.setOnClickListener(iconOnclicks[i]);
			listtemp.put(ii.position+"", ii);
		}

		int[] allp = new int[listtemp.size()];

		for(int i=0;i<listtemp.size();i++){
			IconInfo it = listtemp.get((i+1)+"");
			allp[i] = it.position;
		}

		int[] cll = Arithmetic.sort(allp);

		for(int i=0;i<listtemp.size();i++){
			if(listtemp.get(cll[i]+"").isShow==1){
				list.add(listtemp.get(cll[i]+""));
			}
		}

		MyAdapter adapter = new MyAdapter();
		gv.setAdapter(adapter);

		Lv_Adapter lvadapter = new Lv_Adapter();
		lv.setAdapter(lvadapter);
	}

	public int[] getShow(){
		String mainviewIconVisible = DBHelp.getConfigValue(this, ConfigKey.mainviewIconVisible+";"+fp.getUserguid());
		if(mainviewIconVisible.equals("")){
			for(int i=0;i<pmv.getPositions().length;i++){
				mainviewIconVisible += "1;";
			}
			DBHelp.setConfigValue(this, ConfigKey.mainviewIconVisible+";"+fp.getUserguid(),mainviewIconVisible);
		}

		mainviewIconVisible = DBHelp.getConfigValue(this, ConfigKey.mainviewIconVisible+";"+fp.getUserguid());
		String[] mainviewIconVisibles = mainviewIconVisible.split(";");
		int[] show = new int[pmv.getPositions().length];
		for(int i=0;i<mainviewIconVisibles.length;i++){
			show[i] = Integer.parseInt(mainviewIconVisibles[i]);
		}
		return show;
	}

	public static void showWelcome(SuperView con)
	{
		String showMsg = "<big>"+con.fp.getDisplayname()+"，欢迎您！</big>";
		String unreadMailNums = con.getIntent().getStringExtra("unreadMailNums");
		MailMain.mailNums = Integer.parseInt(unreadMailNums.equals("")?"0":unreadMailNums);
		if(!unreadMailNums.equals("0")&&!unreadMailNums.equals(""))
		{
			showMsg += "<br/><big><font color=red>您当前有"+unreadMailNums+"封未读邮件！</big></font>";
			ToastHelp.showToastCommonLongHtml(con,showMsg);
		}
	}

	public static void Tip(SuperView con)
	{
		if(DBHelp.getConfigValue(con, ConfigKey.isMessageTip).equals("1")){
			MainService.isNetCheck = true;
			if(MainService.netcheckThread!=null){	
				MainService.netcheckThread.interrupt();
			}
		}
		else{
			MainService.isNetCheck = false;
		}
	}

	public static void DS(final SuperView con)
	{
		int user_count = DBHelp.getUserNums(con);
		int ou_count = DBHelp.getOuCount(con);
		if(user_count==0&&ou_count==0){
			/*epointDialog = EpointDialog.getDialog(
					this, 
					"系统检测到您还未同步组织架构，这将会影响到软件更多功能的使用，立即同步组织架构吗？", 
					3, 
					new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							DSView.ds(MainView.this);
							epointDialog.dismiss();
						}
					});
			epointDialog.show();*/

			final SuperDialog sd = new SuperDialog(con);
			sd.setCancelable(false);
			sd.setNegativeButton("立即同步", new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					DSView.ds(con);
					sd.dismiss();
				}
			})

			.setMessage("系统检测到您还未同步组织架构，这将会影响到软件更多功能的使用，立即同步组织架构吗？")
			.show();
		}

	}

	public static void ShowUpdate(final SuperView con)
	{
		//是否有客户端更新
		final Handler handler = new Handler();
		//软件更新提示
		if(PropertiesHelp.getProperty(con, "mainviewCheckClientUptate").equals("1")){
			new Thread(){
				public void run() {
					try{
						String url = FrameMethod.getUpdateXMLUrl(con.fp,con);
						String bs = HttpHelp.getHttpBackNoZipNoCheck(url);
						if(bs.contains(HttpHelp.CONNECTION_TIME_OUT)){
						}
						else{
							String versionStr = StringHelp.getXMLAtt(bs, "version");
							String name = StringHelp.getXMLAtt(bs, "name");
							int remoteversion = FrameMethod.versionToInteger(versionStr);
							int localversion = FrameMethod.versionToInteger(con.getString(R.string.version));
							final String fullfilename = name+"_V"+versionStr+".apk";
							final String clientname = StringHelp.getXMLAtt(bs, "clientname");
							final String updateinfo = StringHelp.getXMLAtt(bs, "updateinfo");

							String msg = "\n检测到可用的升级软件"+fullfilename+"，是否立即更新？";
							if(updateinfo.length()>0){
								msg += "\n"+updateinfo;
							}

							final String fmsg = msg;
							if(remoteversion>localversion){
								handler.post(new Runnable() {

									@Override
									public void run() {

										AlertHelp.ShowAlert(con,fmsg, new OnClickListener() {

											@Override
											public void onClick(DialogInterface dialog, int which) {
												String url = FrameMethod.getUpdateAPKUrl(con.fp, con, clientname);

												//													PhoneHelp.invokeSystemBrowser(MainView.this, url);
												Intent it = new Intent(con,UpdateView.class);
												it.putExtra("enterfalg", 1);
												it.putExtra("url", url);
												it.putExtra("fullfilename", fullfilename);
												con.startActivity(it);
											}
										});
									}
								});
							}
							else{
								handler.post(new Runnable() {

									@Override
									public void run() {
										System.out.println("无软件更新");
										DS(con);
									}
								});
							}
						}

					}catch(Exception e){
						e.printStackTrace();
					}

				};
			}.start();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

		IconInfo intenticon =  list.get(position);
		if(intenticon.getOnClickListener()!=null){
			intenticon.executeOnClickListener();
			return;
		}

		if(intenticon.intentviews.getName().toLowerCase().contains("kaoqing")){
			if(DBHelp.getConfigValue(this, com.epoint.mobileoa.personalized.epointcompany.config.ConfigKey.QDType).equals("1")){
				intenticon.intentviews = KaoQingDetailView.class;
			}
		}

		Intent it = new Intent(this, intenticon.intentviews);
		startActivity(it);
	}

	//选中图标名称
	private String title = "";
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		if(parent==gv){
			LinearLayout ll = (LinearLayout) parent.getChildAt(position);
			TextView tv = (TextView) ll.getChildAt(1);
			title = tv.getText()+"";
		}
		else{
			RelativeLayout rl = (RelativeLayout) parent.getChildAt(position);
			LinearLayout ll = (LinearLayout)rl.getChildAt(2);
			TextView tv = (TextView) ll.getChildAt(0);
			title = tv.getText()+"";
		}
		AlertHelp.showAlertMenu(this, "操作", new String[]{"隐藏","恢复"}, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(which==0){
					if(title.equals("系统设置")){
						ToastHelp.showToast(MainView.this, "无法隐藏该模块");
					}

					else{
						int sortposition = 0;

						for(int i=0;i<pmv.getTitles().length;i++){
							if(pmv.getTitles()[i].equals(title)){
								sortposition = i;
							}
						}

						int[] show = getShow();
						show[sortposition] = 0;
						String showStr = "";

						for(int i=0;i<show.length;i++){
							showStr += show[i]+";";
						}

						DBHelp.setConfigValue(MainView.this, ConfigKey.mainviewIconVisible+";"+fp.getUserguid(), showStr);

						setIcon();
					}
				}
				else if(which==1){
					String mainviewIconVisible = "";
					for(int i=0;i<pmv.getPositions().length;i++){
						mainviewIconVisible += "1;";
					}
					DBHelp.setConfigValue(MainView.this, ConfigKey.mainviewIconVisible+";"+fp.getUserguid(),mainviewIconVisible);
					setIcon();
				}
			}
		});

		return super.onItemLongClick(parent, view, position, id);
	}

	@Override
	public int getLayoutInt() {
		return R.layout.main;
	}

	@Override
	public void refresh(Object... param){

	}

	/*
	 * 更新UI线程，十秒钟更新一次，读取当前网络状态，不通则提示离线
	 */
	@Override
	public void onResume() {
		super.onResume();
		//设置登陆页背景主题
		if(getBackgroundStr().equals("background"))
			mainFrame.setBackgroundResource(R.drawable.background);
		else
			mainFrame.setBackgroundResource(R.drawable.mainbg);

		setIcon();

		String displayType = DBHelp.getConfigValue(this, ConfigKey.displayType);
		if(displayType.equals("1")){
			lv.setVisibility(View.VISIBLE);
			gv.setVisibility(View.GONE);
		}
		else{
			gv.setVisibility(View.VISIBLE);
			lv.setVisibility(View.GONE);
		}

		isUpdateName = true;

		updateNameThread = new Thread(){
			public void run() {
				while(MainService.isrun1){
					if(isUpdateName){
						String display = "<font color=yellow>"+fp.getDisplayname()+"</font>";
						if(!MainService.NetIsOk){
							display += "<font color=red>("+getString(R.string.offline)+")</font>";
						}
						final String dis = display;
						new Handler().post(new Runnable() {
							@Override
							public void run() {

								title_tv_realname.setText(Html.fromHtml(dis));

								if(MainService.lastallmailnums>0){
									ivMailTip.setVisibility(View.VISIBLE);
								}
								else{
									ivMailTip.setVisibility(View.GONE);
								}
							}
						});
					}

					try {
						sleep(5*1000);
					} catch (InterruptedException e) {
						LogHelp.LogI("更新主界面姓名线程休眠中断！");
					}
				}
			}
		};
		updateNameThread.start();


	}



	@Override
	public void onPause() {
		super.onPause();
		isUpdateName = false;
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		pmv.onCreateOptionsMenu(menu);
		return super.onCreateOptionsMenu(menu);
	}

	public void superOnOptionsItemSelected(MenuItem item) {
		pmv.OnOptionsItemSelected(item);
	}

	@Override
	public void KEYCODE_BACK() {
		quitApp(this);

	}

	public static void quitApp(final Activity con){

		/*epointDialog = EpointDialog.getDialog(
				con, 
				"您要退出程序吗？", 
				2, 
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						MainService.quitApplication(con);
						NotificationManager manager = (NotificationManager) con.getSystemService(NOTIFICATION_SERVICE);
						manager.cancel(MainService.MAIL_NOTIFICATION_FLAG);
						epointDialog.dismiss();
					}
				});
		epointDialog.show();*/
		final SuperDialog sv = new SuperDialog(con);
		sv.setPositiveButton("确定", new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				MainService.quitApplication(con);
				NotificationManager manager = (NotificationManager) con.getSystemService(NOTIFICATION_SERVICE);
				manager.cancel(MainService.MAIL_NOTIFICATION_FLAG);
				sv.dismiss();
			}
		})
		.setMessage("您要退出程序吗？")
		.setNegativeButton("取消", null)
		.show();


	}
	@Override
	public String setTitle() {
		return "首页";
	}
	public static void quitLogin(Activity con){
		Intent it_login = new Intent(con,LoginView.class);
		con.startActivity(it_login);
		con.finish();
		//取消自动登录
		DBHelp.setConfigValue(con,ConfigKey.autologin, "0");
		NotificationManager manager = (NotificationManager) con.getSystemService(NOTIFICATION_SERVICE);
		manager.cancel(MainService.MAIL_NOTIFICATION_FLAG);
	}

	class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {

			return list.size();

		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				LayoutInflater mInflater = LayoutInflater.from(MainView.this);
				convertView = mInflater.inflate(R.layout.iconlayout, null);

				holder.iv = (ImageView) convertView
						.findViewById(R.id.ivIcoImg);
				holder.tv = (TextView) convertView.findViewById(R.id.tvIcoTitle);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			IconInfo iifo = list.get(position);

			holder.iv.setImageResource(iifo.iconImage);
			holder.tv.setText(iifo.iconTitle);

			setTextViewFontColor(holder.tv);

			return convertView;
		}

	}

	public class ViewHolder {
		public ImageView iv;
		public TextView tv;
	}

	class Lv_Adapter extends BaseAdapter{

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder_LV holder = null;
			if (convertView == null) {
				holder = new ViewHolder_LV();
				LayoutInflater mInflater = LayoutInflater.from(MainView.this);
				convertView = mInflater.inflate(R.layout.lv_main, null);
				holder.ivLeft = (ImageView) convertView
						.findViewById(R.id.ivIconLeft);
				holder.ivRight = (ImageView) convertView
						.findViewById(R.id.ivImgRight);
				holder.tvTop = (TextView) convertView
						.findViewById(R.id.tvTitle);
				holder.tvBottom = (TextView) convertView
						.findViewById(R.id.tvInfo);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder_LV) convertView.getTag();
			}
			IconInfo i = list.get(position);
			holder.ivLeft.setImageResource(i.iconImage);
			holder.ivRight.setImageResource(R.drawable.img_sys_lvright1);
			holder.tvTop.setText(i.iconTitle);
			holder.tvBottom.setVisibility(View.GONE);
			setTextViewFontColor(holder.tvTop);
			return convertView;
		}
	}

	public class ViewHolder_LV {
		public ImageView ivLeft;
		public ImageView ivRight;
		public TextView tvTop;
		public TextView tvBottom;
	}

	@Override
	public void refreshForNewTask(int TaskId,Object... param) {
	}

}